<template>
  <div>
    <el-breadcrumb separator="/" style="padding-left:10px;padding-bottom:10px;font-size:12px;">
      <el-breadcrumb-item :to="{ path: '/main' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>系统管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色管理</el-breadcrumb-item>
    </el-breadcrumb>
      <el-card>
      <el-form :inline="true" :model="roleVo" class="demo-form-inline">
        <el-form-item label="角色名称" label-width="70px">
          <el-input clearable v-model="roleVo.roleName" placeholder="请输入角色名称"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" label-width="70px">
          <el-input clearable v-model="roleVo.remark" placeholder="请输入角色描述"></el-input>
        </el-form-item>
        <el-form-item style="margin-left: 10px">
          <el-button icon="el-icon-refresh" @click="resetRoleVo">重置</el-button>
          <el-button type="primary" icon="el-icon-search" @click="getRoleList">查询</el-button>
          <el-button type="success" icon="el-icon-plus" @click="show">添加</el-button>
        </el-form-item>
      </el-form>
      <!--表格-->
      <el-table
        :data="roleList"
        border
        max-height="100%"
        style="width: 100%;">
        <el-table-column
          prop="id"
          label="ID"
          width="100">
        </el-table-column>
        <el-table-column
          prop="roleName"
          label="角色名称"
          width="900">
        </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scop">
            <el-button type="primary" size="mini" icon="el-icon-edit" @click="edit(scop.row.id)"></el-button>
            <el-button type="danger" size="mini" icon="el-icon-delete" @click="del(scop.row.id)"></el-button>
            <el-tooltip
              class="item"
              effect="dark"
              content="授权"
              placement="top"
              :enterable="false"
            >
              <el-button
                type="warning"
                size="mini"
                icon="el-icon-document-add"
                @click="assignRoles(scop.row.id)"
              ></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        style="padding-top: 15px"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"

        :current-page="current"
        :page-sizes="[6, 10, 20, 30,60]"
        :page-size="size"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total">
      </el-pagination>

      <!-- 修改对话框 -->
      <el-dialog title="修改角色" :visible.sync="editDialogVisible" width="50%" @close="editClose">
        <span>
          <el-form
            :model="editForm"
            :label-position="labelPosition"
            :rules="addFormRules"
            ref="editFormRef"
            label-width="80px"
          >
            <el-row>
              <el-col :span="10">
                <div class="grid-content bg-purple">
                  <el-form-item label="角色名称" prop="roleName">
                    <el-input v-model="editForm.roleName"></el-input>
                     <el-input
                       type="hidden"
                       v-model="editForm.id"
                       :disabled="true"
                       style="display:none;"
                     ></el-input>
                  </el-form-item>
                </div>
              </el-col>
               <el-col :span="20">
                <div class="grid-content bg-purple">
                  <el-form-item label="角色描述" prop="remark">
                    <el-input v-model="editForm.remark"></el-input>
                  </el-form-item>
                </div>
              </el-col>
            </el-row>
          </el-form>
        </span>

        <span slot="footer" class="dialog-footer">
          <el-button @click="editDialogVisible = false">取 消</el-button>
          <el-button
            type="primary"
            @click="updateRole"
            :loading="btnLoading"
            :disabled="btnDisabled"
          >确 定</el-button>
        </span>
      </el-dialog>

      <!-- 添加对话框 -->
      <el-dialog title="添加角色" :visible.sync="addDialogVisible" width="50%" @close="editClose">
        <span>
          <el-form
            :model="editForm"
            :label-position="labelPosition"
            :rules="addFormRules"
            ref="editFormRef"
            label-width="80px"
          >
            <el-row>
              <el-col :span="10">
                <div class="grid-content bg-purple">
                  <el-form-item label="角色名称" prop="roleName">
                    <el-input v-model="editForm.roleName"></el-input>
                  </el-form-item>
                </div>
              </el-col>
               <el-col :span="20">
                <div class="grid-content bg-purple">
                  <el-form-item label="角色描述" prop="remark">
                    <el-input v-model="editForm.remark"></el-input>
                  </el-form-item>
                </div>
              </el-col>
            </el-row>
          </el-form>
        </span>

        <span slot="footer" class="dialog-footer">
          <el-button @click="addDialogVisible = false">取 消</el-button>
          <el-button
            type="primary"
            @click="addRole"
            :loading="btnLoading"
            :disabled="btnDisabled"
          >确 定</el-button>
        </span>
      </el-dialog>

      <!-- 角色授权对话框 -->
      <el-dialog center title="授权" :visible.sync="assignDialogVisible" width="49%">
        <span>
          <template>
            <el-tree
              ref="tree_right"
              :data="data"
              show-checkbox
              node-key="id"
              v-model="value"
              @check-change="handleCheckChange"
              :props="defaultProps"
              :default-checked-keys="defaultSelect">
            </el-tree>
          </template>
        </span>
        <span slot="footer" class="dialog-footer">
          <el-button @click="assignDialogVisible = false" class="el-icon-close">取消</el-button>
          <el-button
            type="primary"
            @click="doAssignRoles"
            class="el-icon-check"
            :loading="btnLoading"
            :disabled="btnDisabled"
          >确定</el-button>
        </span>
      </el-dialog>
    </el-card>
  </div>
</template>

<script>
import { addRole, deleteRole, findRolePage, menuAuth, queryMenuList, roleDetail, updateRole ,getMenuByRoleId} from '@/api/Users'

export default {
  name: 'Roles',
  data() {
    return {
      roleVo: {
        roleName: "",
        remark: ""
      },
      roleList: [],
      //每页显示的条数
      size: 6,
      //总条数
      total: 100,
      //当前页码
      current: 1,
      editDialogVisible:false,   //修改对话框
      addDialogVisible:false,   //添加对话框
      editForm: {}, //更新表单
      labelPosition: "right",  //lable对齐方式
      btnLoading: false,
      btnDisabled: false,
      assignDialogVisible: false, //角色授权对话框
      addFormRules: {
        roleName: [
          { required: true, message: "请输入角色名称", trigger: "blur" },
          { min: 1, max: 16, message: "长度不能超过 16 个字符", trigger: "blur" }
        ],
        remark: [
          { required: true, message: "请输入角色描述", trigger: "blur" },
          { min: 1, max: 50, message: "长度不能超过 50 个字符", trigger: "blur" }
        ]
      }, //添加表单验证规则
      userKeyWord: {
        keyWord: "",
        type: "0"
      },
      data:[],
      defaultProps: {
        children: 'children',
        label: 'menuName',
        key: 'id',
      },
      value:[], //菜单集合
      roleMenu: [], //菜单授权集合
      roleId:"",
      defaultSelect:[]
    };
  },
  mounted () {
    this.getRoleList();
  },
  methods:{
    //当每页条数改变的时候
    handleSizeChange (val) {
      //将val赋值到size
      this.size = val;
      //重新到后台查询
      this.getRoleList();
    },
    //当前页码改变的时候
    handleCurrentChange (val) {
      this.current=val;
      this.getRoleList();
    },
    async getRoleList(){
      const { data } =await findRolePage(this.current,this.size,this.roleVo)
      this.roleList=data.data.roleList;
      this.total=data.data.total;
    },
    resetRoleVo(){
      this.roleVo.roleName=''
      this.roleVo.remark=''
      this.getRoleList()
    },
    /**
     * 角色信息详情
     */
    async edit(id) {
      const { data: res } = await roleDetail(id);
      if (res.code == 200) {
        console.log(res.data.records)
        this.editForm = res.data.records;
        this.editDialogVisible = true;
      } else {
        return this.$message.error("角色信息编辑失败:" + res.msg);
      }
    },
    /**
     * 关闭编辑弹出框
     */
    editClose() {
      this.$refs.editFormRef.clearValidate();
      this.editForm = {};
    },
    /**
     * 更新角色
     * @returns {Promise<void>}
     */
    async updateRole(){
      this.$refs.editFormRef.validate(async valid =>{
        if (!valid){
          return;
        }else {
          this.btnLoading = true;
          this.btnDisabled = true;
          this.editForm.createTime='';
          this.editForm.modifiedTime='';
          this.editForm.status='';
          const { data: res} =await updateRole(this.editForm)
          if (res.code=='200'){
            this.$notify({
              title: "操作成功",
              message: "角色基本信息已更新",
              type: "success"
            });
            this.editForm = {};
            this.getRoleList();
          }else {
            this.$message.error(res.message);
          }
          this.editDialogVisible = false;
          this.btnLoading = false;
          this.btnDisabled = false;
        }
      });
    },
    /**
     * 删除角色信息
     * @param id
     * @returns {Promise<void>}
     */
    async del(id){
      var res = await this.$confirm(
        "此操作将永久删除该角色, 是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }
      ).catch(() => {
        this.$message({
          type: "info",
          message: "已取消删除"
        });
      });
      if (res == "confirm"){
        const { data: res } =await deleteRole(id)
        console.log(res)
        if (res.code == 200) {
          this.$notify.success({
            title:'操作成功',
            message:'角色删除成功',
          });
          this.getRoleList();
        } else {
          this.$message.error(res.message);
        }
      }
    },
    // 按钮点击事件 显示新增编辑弹窗组件
    show(){
      this.addDialogVisible = true
    },
    /**
     * 添加角色
     * @returns {Promise<void>}
     */
    async addRole(){
      this.$refs.editFormRef.validate(async valid =>{
        if (!valid){
          return;
        }else {
          this.btnLoading = true;
          this.btnDisabled = true;
          const { data: res} =await addRole(this.editForm)
          if (res.code=='200'){
            this.$notify.success({
              title: '操作成功',
              message: '角色添加成功',
            })
            this.editForm = {};
            this.getRoleList();
          }else {
            this.$message.error(res.message);
          }
          this.addDialogVisible = false;
          this.btnLoading = false;
          this.btnDisabled = false;
        }
      });
    },
    /**
     * 弹出角色授权
     */
    async assignRoles(id) {
      this.roleId=id;
      this.assignDialogVisible = true;
      this.defaultSelect=[],
      this.queryMenuList();
      this.getMenuByRoleId(id);
    },
    /**
     * 菜单列表
     * @returns {Promise<void>}
     */
    async queryMenuList(){
      const {data:res} =await queryMenuList(this.userKeyWord);
      if (res.code==200){
        console.log(res.data.menuList);
        this.data=res.data.menuList;
      }else {
        this.$message.error( res.message);
      }
    },
    /**
     * 确认授权
     * @returns {Promise<void>}
     */
    async doAssignRoles(){
      console.log(this.roleMenu)
      if (!this.roleMenu.length){
        this.$message.error( "请为角色授权");
      }else {
        const {data:res} =await menuAuth(this.roleMenu);
        if (res.code=='200'){
          this.$notify.success({
            title: '操作成功',
            message: '角色授权成功',
          })
          this.assignDialogVisible = false;
          this.getRoleList();
        }else {
          this.$message.error(res.message);
        }
      }

    },
    async handleCheckChange(){
      //返回半选中和选中的节点
      let keyList=this.$refs.tree_right.getCheckedNodes(false ,true )
      console.log(keyList)
      let arr=[];
      keyList.forEach((item)=>{
        arr.push({menuId:item.id,roleId:this.roleId})
      })
      this.roleMenu=arr
    },
    /**
     * 查询角色已绑定的菜单
     * @param id
     * @returns {Promise<void>}
     */
    async getMenuByRoleId(id){
      const {data: res} = await getMenuByRoleId(id);
      console.log(res.data.menuList);
      this.defaultSelect=res.data.menuList;
    }
  }
}
</script>

<style lang="less" scoped>
.role-card {
  margin-top: 20px;
}
.option-box {
  overflow: hidden;
  margin-bottom: 10px;
}
</style>
